/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.service.office.impl;

import cn.hutool.core.io.IoUtil;
import com.je.common.base.DynaBean;
import com.je.common.base.document.DocumentPreviewWayEnum;
import com.je.common.base.util.AsposeUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.document.model.FileBO;
import com.je.document.model.FileUpload;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class OfficePdfPreviewServiceImpl extends AbstractOfficePreviewService {

    private static final Logger logger = LoggerFactory.getLogger(OfficePdfPreviewServiceImpl.class);

    @Override
    public String getPreviewUrl(String fileKey) {
        String userId = SecurityUserHolder.getCurrentAccountRealUser() == null ? "" : SecurityUserHolder.getCurrentAccountRealUser().getId();
        String previewFileKey = getOfficeToPdfPreviewFileKey(fileKey, userId);
        return String.format("/je/document/preview/%s", previewFileKey);
    }

    private String getOfficeToPdfPreviewFileKey(String fileKey, String userId) {
        DynaBean relDynaBean = metaService.selectOne("JE_DOCUMENT_REL", ConditionsWrapper.builder().eq("file_key", fileKey));
        DynaBean fileDynaBean = metaService.selectOneByPk("JE_DOCUMENT_FILE", relDynaBean.getStr("file_id"));
        DocumentPreviewWayEnum documentPreviewWayEnum = systemSettingRpcService.getDocumentPreviewWayByFileSuffix(fileDynaBean.getStr("suffix"));
        if (documentPreviewWayEnum == null || !"pdf".equals(documentPreviewWayEnum.getType())) {
            return fileKey;
        }

        if (StringUtil.isNotEmpty(relDynaBean.getStr("pdf_file_Key"))) {
            return relDynaBean.getStr("pdf_file_Key");
        }

        //将该文件转为pdf
        FileBO fileBO = documentBusService.previewFile(fileKey, userId);
        FileBO fileBOPdf = toPdf(fileDynaBean.getStr("suffix"), fileBO.getFile(), fileBO.getRelName());
        if (fileBOPdf.getFile() == null) {
            return fileKey;
        }

        List<FileUpload> fileUploadFiles = new ArrayList<>();
        FileUpload fileUpload = new FileUpload(fileDynaBean.getStr("name") + ".pdf", "application/pdf", fileBOPdf.getSize(), fileBOPdf.getFile());
        fileUploadFiles.add(fileUpload);
        List<FileBO> fileBOS = documentBusService.saveFile(fileUploadFiles, userId, null, fileDynaBean.getStr("bucket"), null);
        if (fileBOS == null || fileBOS.size() == 0) {
            return fileKey;
        }
        //保存pdfFileKey
        String pdfFileKey = fileBOS.get(0).getFileKey();
        relDynaBean.setStr("pdf_file_Key", pdfFileKey);
        metaService.update(relDynaBean);
        return pdfFileKey;
    }

    private FileBO toPdf(String suffix, InputStream inputStream, String relName) {
        FileBO fileBO = new FileBO();
        ByteArrayInputStream byteArrayInputStream = null;
        byte[] content = null;
        if ("docx".equals(suffix) || "doc".equals(suffix)) {
            content = AsposeUtils.wordToPdf(IoUtil.readBytes(inputStream));
        }

        if ("xls".equals(suffix) || "xlsx".equals(suffix)) {
            content = AsposeUtils.excelToPdf(IoUtil.readBytes(inputStream));
        }

        if ("ppt".equals(suffix)) {
            byte[] bytes = IoUtil.readBytes(inputStream);
            content = AsposeUtils.pptToPdf(bytes);
        }

        if ("pptx".equals(suffix)) {
            byte[] bytes = IoUtil.readBytes(inputStream);
            content = AsposeUtils.pptxToPdf(bytes);
        }
        fileBO.setSize((long) content.length);
        byteArrayInputStream = IoUtil.toStream(content);
        fileBO.setFile(byteArrayInputStream);
        return fileBO;
    }

}
